<template>
    <Card style="margin-top: 20px">
      <Row :gutter="2" style="margin-bottom: 25px">
        <i-col style="text-align: center" span="3" v-if="$store.state.user.avatar !== ''">
          <Avatar :src="$store.state.user.avatar" size="40"></Avatar>
        </i-col>
        <i-col span="18">
          <i-input @on-blur="onBlur" v-model="comment" type="textarea" :disabled="!isEdit"
                   maxlength="500" show-word-limit ref="inputComment" :autofocus="true"
                   :autosize="{minRows: 2,maxRows: 5}" :placeholder="placeholder"/>
        </i-col>
        <i-col span="3">
          <div v-if="!isEdit">
            <i-button @click="startComment">评论</i-button>
          </div>
          <div v-if="isEdit">
            <i-button type="info" @click="publishComment">发表评论</i-button>
            <div style="margin-top: 10px">
              <i-button type="error" @click="cancelComment">取消评论</i-button>
            </div>
          </div>
        </i-col>
      </Row>
      <List>
        <div v-for="(item, index) in commentVoList" :key="index">
          <ListItem >
            <ListItemMeta :avatar="item.avatar" :title="item.nickname" :description="item.content" />
            {{item.gmtCreate | time}}
            <Avatar style="margin-left: 20px"  v-if="item.position" src="http://dd.ddandang.top/blog/images/admin.png" size="30"/>
            <template slot="action">
              <li>
                <a @click="reply(item.id, item.nickname)">回复</a>
              </li>
              <!--后台才显示-->
              <li v-if="allowDeleteAndUpdate">
                <a v-if="!item.topping" @click="updateTop(item.id, item.topping)">置顶</a>
                <a v-else @click="updateTop(item.id, item.topping)">取消置顶</a>
              </li>
              <li v-if="item.userId === $store.state.user.userId || allowDeleteAndUpdate">
                <a @click="deleteComment(item.id)" style="color: red">删除</a>
              </li>
            </template>
          </ListItem>
          <Divider />

          <List v-if="item.childrenComments.length !== 0" style="margin-left: 50px">
            <ListItem v-for="(children, index) in item.childrenComments" :key="index">
              <ListItemMeta :avatar="children.avatar" :title="children.nickname" :description="children.content" />
              {{children.gmtCreate | time}}
              <Avatar style="margin-left: 20px" v-if="children.position" src="http://dd.ddandang.top/blog/images/admin.png" size="30"/>
              <template slot="action">
                <!--后台才显示-->
                <li v-if="allowDeleteAndUpdate">
                  <a v-if="!children.topping" @click="updateTop(children.id, children.topping)">置顶</a>
                  <a v-else @click="updateTop(children.id, children.topping)">取消置顶</a>
                </li>
                <li v-if="children.userId === $store.state.user.userId || allowDeleteAndUpdate">
                  <a @click="deleteComment(children.id)" style="color: red">删除</a>
                </li>
              </template>
            </ListItem>
          </List>
        </div>
      </List>
      <!--分页-->
      <div style="margin-top: 60px;text-align: center">
        <Page :current="pageNo" v-if="total>pageSize" @on-change="changeSize" :page-size="pageSize" :total="total" show-total/>
      </div>
    </Card>
</template>

<script>
  import {deleteComment, insertComment, listCommentVo, updateCommentTop} from "@/network/comment";
  import moment from "moment";

  export default {
    name: "Comment",
    props: {
      allowComment: {
        type: Boolean,
        require: true
      },
      allowDeleteAndUpdate: {
        type: Boolean,
        require: false
      },
      articleId: {
        type: Number,
        require: true
      }
    },
    data() {
      return {
        //评论显示10条父评论
        pageNo: 1,
        pageSize: 10,
        total: 0,
        //获取的文章信息
        articleInfo: {},
        //全部分类
        categoryList: [],
        //分类中的文章
        articleList: [],
        //文章点击数
        hits: 0,
        //文章评论数
        commentAmount: 0,
        //评论
        comment: '',
        //是否可以评论
        isEdit: false,
        //输入框中显示的提示文字
        placeholder: '请输入评论内容。。。',
        //是否聚焦
        isFocus: false,
        //父评论Id
        parentCommentId: 0,
        commentVoList: []
      }
    },
    mounted() {
      //获取文章的评论
      this.listCommentVo();
    },
    methods: {
      startComment() {
        if(!this.allowComment) {
          this.$Message.error({
            background: true,
            content: '这篇文章不允许评论！'
          })
          return;
        }
        //未登录不允许评论
        if(this.$store.state.token === '') {
          this.$Message.error({
            background: true,
            content: '请先进行登录！'
          })
          return;
        }
        this.isEdit = true;

      },
      //输入框失去焦点
      onBlur() {
        if(this.comment === '') {
          this.isEdit = false;
          this.parentCommentId = 0;
        }
        this.placeholder = '请输入评论内容。。。';
      },
      cancelComment() {
        this.comment = '';
        this.isEdit = false;
        this.placeholder = '请输入评论内容。。。';
        this.parentCommentId = 0;
      },
      //发布评论
      publishComment() {
        //防止按钮闪烁（失去焦点变动）
        if(this.comment === '') {
          this.$Message.error("评论不能为空!");
          return;
        }
        insertComment(this.articleId, this.parentCommentId, this.comment, this.$store.state.user.userId)
            .then(res => {
              if(res.code === 2000) {
                this.$Message.success("评论成功!");
                this.cancelComment();
                //获取文章的评论
                this.listCommentVo();
              }
            }).catch(() => {
          this.$Message.error("评论失败!");
        })
      },
      //获取评论数据
      listCommentVo() {
        listCommentVo(this.pageNo, this.pageSize, this.articleId).then(res => {
          if(res.code === 2000) {
            this.commentVoList = res.data.commentVoList;
            this.total = res.data.total;
          }

        })
      },
      //回复
      reply(commentId, nickname) {
        this.isEdit = true;
        this.placeholder = '回复：' + nickname;
        this.parentCommentId = commentId;
        this.$refs['inputComment'].focus();

      },
      //改变页码
      changeSize(pageNo) {
        //当前页码与点击的不同再进行请求数据
        if(this.pageNo !== pageNo) {
          this.pageNo = pageNo;
          //获取文章的评论
          this.listCommentVo();
        }
      },
      //删除评论
      deleteComment(commentId) {
        deleteComment(commentId).then(res => {
          if(res.code === 2000) {
            this.$Message.success('删除评论成功！');
            //获取文章的评论
            this.listCommentVo();
            return;
          }
          this.$Message.error('删除评论失败！');
        })
      },
      //更新置顶状态
      updateTop(commentId, top) {
        updateCommentTop(commentId, !top).then(res => {
          if(res.code === 2000) {
            this.$Message.success('更新置顶成功！');
            //获取文章的评论
            this.listCommentVo();
            return;
          }
          this.$Message.error('更新置顶失败！');
        })
      }
    },
    filters: {
      time: function (date) {
        return moment(date).startOf('hour').fromNow();
      }
    },
    watch: {
      //检测这个值的变化然后更新评论
      articleId: function () {
        //获取文章的评论
        this.listCommentVo();
      }
    }
  }
</script>

<style scoped>

</style>